<?php

namespace App\Jobs;

use App\Services\UserService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Redis;

class UserQueue implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $params;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($params)
    {
        $this->params = $params;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $parms = $this->params;
        $data = $parms['data'];

        $action = $parms['action'];

        $result = $this->$action($data);

        return $result;
    }

    /*
     * 创建用户唯一编码
     * */
    private function create_user_code($data)
    {
        // 锁机制
        $key = config('feild.redis.task.user_invitation_code.key');
        $lock_time = config('feild.redis.task.user_invitation_code.max_lock_time');
        $flag = true;
        while ($flag == true){
            // 没有任务在执行
            if(empty(Redis::get($key)))
                $flag = false;
        }

        // 锁定默认时间
        Redis::setex($key, $lock_time, 1);

        if(!isset($data['uid']) || empty($data['uid']))
            return false;

        // 创建用户二维码
        $result = UserService::create_user_code($data['uid']);

        // 删除锁定
        Redis::del($key);
    }

}
